package com.zjl.学习.第06章_块步骤_读操作写.C_ItemWriter写;

import com.zjl.学习.第06章_块步骤_读操作写.User;
import org.springframework.batch.item.database.ItemPreparedStatementSetter;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * ClassName: B3_输出到数据库
 * Package: com.zjl.学习.第06章_块步骤_读操作写.C_ItemWriter写
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2024/8/4 12:09
 * @Version 1.0
 */
public class B3_输出到数据库 {

    @Autowired
    private DataSource dataSource;
    @Bean
    public UserPreStatementSetter preStatementSetter(){
        return new UserPreStatementSetter();
    }
    @Bean
    public JdbcBatchItemWriter<User> itemWriter(){
        return new JdbcBatchItemWriterBuilder<User>()
                .dataSource(dataSource)
                .sql("insert into user(id, name, age) values(?,?,?)")
                .itemPreparedStatementSetter(preStatementSetter())
                .build();
    }
}
@Component
//写入数据库需要操作insert sql， 使用预编译就需要明确指定参数值
class UserPreStatementSetter implements ItemPreparedStatementSetter<User> {
    @Override
    public void setValues(User item, PreparedStatement ps) throws SQLException {
        ps.setLong(1, item.getId());
        ps.setString(2, item.getName());
        ps.setInt(3, item.getAge());
        ps.setString(4, "男");
    }
}

